<template>
  <a-modal
    :visible="visible"
    title="新增用户"
    cancelText="取消"
    okText="提交"
    width="1200px"
    @ok="submit"
    @cancel="cancel"
  >
    <div>
      <h3>组卷信息</h3>
      <div style="float: right; font-weight: bold; color: #ff0000">试卷总分：{{ postForm.values.totalScore }}分</div>
      <div style="float: right; font-weight: bold; color: white" v-show="false">aaa：{{ postForm.values.poppp }}分</div>
      <a-button type="primary" @click="aaa">添加题库</a-button>
      <a-form
        style="margin-top: 20px"
        ref="formRef"
        :model="postForm.values.repoList"
        name="advanced_search"
        class="ant-advanced-search-form"
        :label-col="{ span: 7 }"
        :wrapper-col="{ span: 49 }"
        layout="vertical"
        v-if="testShow"
      >
        <a-form-item
          v-for="(domain, index) in postForm.values.repoList"
          :key="domain.key"
          v-bind="index === 0 "
        >
          <a-row>
            <a-col :span="3" style="margin-right: 10px">
              <a-form-item label="归属题库">
                <a-select
                  v-model:value="domain.repoId"
                  placeholder="请选择归属题库"
                  :options=question
                  @change="handleChange(domain)"
                ></a-select>
              </a-form-item>
            </a-col>

            <a-col :span="3" style="margin-right: 10px">
              <a-form-item label="单选数量">
                <a-input-number v-model:value="domain.radioCount" :min="0" :max="domain.totalRadio"
                                @change="totalScoreChange"/>
                /{{ domain.totalRadio }}
              </a-form-item>
            </a-col>

            <a-col :span="3" style="margin-right: 10px">
              <a-form-item label="单选分数">
                <a-input-number v-model:value="domain.radioScore" :min="0" @change="totalScoreChange"/>
              </a-form-item>
            </a-col>
            <a-col :span="3" style="margin-right: 10px">
              <a-form-item label="多选数量">
                <a-input-number v-model:value="domain.multiCount" :min="0" :max="domain.totalMulti" @change="totalScoreChange"/>
                /{{ domain.totalMulti }}
              </a-form-item>
            </a-col>
            <a-col :span="3" style="margin-right: 10px">
              <a-form-item label="多选分数">
                <a-input-number v-model:value="domain.multiScore" :min="0" @change="totalScoreChange"/>
              </a-form-item>
            </a-col>
            <a-col :span="3" style="margin-right: 10px">
              <a-form-item label="判断题数量">
                <a-input-number v-model:value="domain.judgeCount" :min="0" :max="domain.totalJudge" @change="totalScoreChange"/>
                /{{ domain.totalJudge }}
              </a-form-item>
            </a-col>
            <a-col :span="3">
              <a-form-item label="判断题分数">
                <a-input-number v-model:value="domain.judgeScore" :min="0" @change="totalScoreChange"/>
              </a-form-item>
            </a-col>
          </a-row>
          <MinusCircleOutlined
            v-if="postForm.values.repoList.length > 1"
            class="dynamic-delete-button"
            :disabled="postForm.values.repoList.length === 1"
            @click="removeDomain(domain)"
          />
        </a-form-item>
      </a-form>

      <h3 style="margin-top: 50px">考试配置</h3>
      <a-form :model="postForm">
        <a-form-item label="考试名称：">
          <a-input v-model:value="postForm.values.title" style="width: 90%;margin-left: 40px "/>
        </a-form-item>
        <a-form-item label="考试描述：">
          <a-input v-model:value="postForm.values.content" style="width: 90%;margin-left: 40px "/>
        </a-form-item>
        <a-form-item label="总 分 数 ：">
          <a-input-number v-model:value="postForm.values.totalScore" :disabled="true" style="width: 200px;margin-left: 46px "/>
        </a-form-item>
        <a-form-item label="及 格 分 ：">
          <a-input-number v-model:value="postForm.values.qualifyScore" :min="0" :max="postForm.values.totalScore"
                          style="width: 200px;margin-left: 46px "/>
        </a-form-item>
        <a-form-item label="考试时长(分钟)：">
          <a-input-number v-model:value="postForm.values.totalTime" :min="0" style="width: 200px; margin-left: 5px "/>
        </a-form-item>
        <a-form-item label="是否限时：">
          <a-switch v-model:checked="postForm.values.timeLimit" style="margin-left: 41px "/>
        </a-form-item>
        <a-form-item label="考试时间：" v-if="postForm.values.timeLimit">
          <a-range-picker
            v-model:value="dateValues"
            style="margin-left: 41px "
            :locale="locale"
            format="YYYY-MM-DD"
            :placeholder="['开始时间', '结束时间']"
            @change="onTimeChange"/>
        </a-form-item>
      </a-form>

      <h3>权限配置</h3>
      <a-radio-group v-model:value="postForm.values.openType" button-style="solid">
        <a-radio-button value="1">完全开放</a-radio-button>
        <a-radio-button value="2" style="margin-left: 20px">部门开放</a-radio-button>
      </a-radio-group>
      <a-alert message="开放的，任何人都可以进行考试！" type="warning" v-if="postForm.values.openType=='1'"
               style="margin-top: 20px"/>
      <pro-table
        v-if="postForm.values.openType=='2'"
        ref="tableRef"
        :fetch="fetch"
        :columns="columns"
        :pagination="pagination"
        :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
      >
      </pro-table>

    </div>
  </a-modal>
</template>
<script>
import {message} from 'ant-design-vue';
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import moment from 'moment'

import {defineComponent, reactive, ref, toRaw, watch} from "vue";
import {MinusCircleOutlined} from '@ant-design/icons-vue';
import {quQuDetail, examSave, fetchDetail} from "../../../api/module/exam";
import {tree} from "../../../api/module/dept";


export default defineComponent({
  components: {
    MinusCircleOutlined,
  },
  props: {
    visible: {
      type: Boolean,
    },
    record: {
      type: Object,
    }
  },
  emit: ["close"],
  setup(props, context) {
    // 部门树所需方法以及参数
    const tableRef = ref()
    /// 数据来源 [模拟]
    const fetch = async () => {
      var response = await tree();
      return {
        data: response.data,
      };
    };
    const columns = [
      {dataIndex: "name", key: "name", title: "部门"},
    ];
    const pagination = false;
    const onSelectChange = selectedRowKeys => {
      console.log("选中-----", selectedRowKeys)
      state.selectedRowKeys = selectedRowKeys;
      postForm.values.departIds = selectedRowKeys;
    };

    const fileList = ref([]);
    const loading = ref(false);
    const imageUrl = ref('');
    const formRef = ref();
    const quTypeDisabled = ref(false);
    let itemImage = true;
    let id = '';
    let dateValues = ref([]);
    // 答案框显示参数
    let testShow = ref(false)
    const state = reactive({
      posts: [],
      depts: [],
      selectedRowKeys: [],
      param: {},
    })
    // 题目内容
    let postForm = reactive({values : {
      // 总分数
      totalScore: 0,
      timeLimit: false,
      totalTime: 0,
      qualifyScore: 0,
      // 题库列表
      repoList: [],
      // 组题方式
      joinType: 1,
      // 开放类型
      openType: "1",
      poppp: 0,
      // 考试班级列表
      departIds: []
    }});
    let levels = [
      {value: 1, label: '普通'},
      {value: 2, label: '较难'}
    ]

    let quTypes = ref([{
      value: 1,
      label: '单选题'
    }, {
      value: 2,
      label: '多选题'
    },
      {
        value: 3,
        label: '判断题'
      }
    ])
    // 题库下拉框
    let question = [];

    const formState = reactive({
      avatar: "",
      enable: true,
      gender: "0",
    });


    watch(props, (props) => {
      id = props.record.id;
      console.log("修改传参+", id)
      if (id != 'undefined' && id != null && id != '') {
        const param = {
          id: id,
        }
        fetchDetail(param).then((response) => {
          // 修改获取页面数据
          testShow.value = true
          postForm.values = response.data
          postForm.values.poppp = 10
          postForm.values.openType = response.data.openType+""
          state.selectedRowKeys = response.data.departIds
          dateValues.value[0] =  postForm.values.startTime
          dateValues.value[1] =  postForm.values.endTime
          // postForm.values.startTime = dateString[0]
          // postForm.values.endTime = dateString[1]
          console.log("返回制：",toRaw(postForm))
        });
      }
    })


    const submit = (e) => {
      console.log("最终提交结果---", toRaw(postForm))
      if (postForm.values.totalScore == 0) {
        message.error("考试规则设置不正确，请确认！")
        return
      }

      if (postForm.values.joinType == 1) {
        for (let i = 0; i < postForm.values.repoList.length; i++) {
          const repo = postForm.values.repoList[i]

          if (!repo.repoId) {
            message.error("考试题库选择不正确！")
            return
          }

          if ((repo.radioCount > 0 && repo.radioScore == 0) || (repo.radioCount == 0 && repo.radioScore > 0)) {
            message.error("题库第：[" + (i + 1) + "]项存在无效的单选题配置！")
            return
          }

          if ((repo.multiCount > 0 && repo.multiScore == 0) || (repo.multiCount == 0 && repo.multiScore > 0)) {
            message.error("题库第：[" + (i + 1) + "]项存在无效的多选题配置！")
            return
          }

          if ((repo.judgeCount > 0 && repo.judgeScore == 0) || (repo.judgeCount == 0 && repo.judgeScore > 0)) {
            message.error("题库第：[" + (i + 1) + "]项存在无效的判断题配置！")
            return
          }
        }
      }
      submitForm()
    };
    // 提交
    const submitForm = () => {
      examSave(toRaw(postForm.values)).then((response) => {
        if (response.success) {
          message.success({content: '保存成功', duration: 1}).then(() => {
            cancel();
          });
        } else {
          message.error({content: '保存失败', duration: 1}).then(() => {
            cancel();
          });
        }
      })
    };
    const cancel = (e) => {
      context.emit("close", false);
    };


    // 获取题库列表
    const getQuestion = () => {
      // list({}).then((response) => {
      //   state.posts = response.data;
      // })
      let response = {
        "code": 0,
        "data": [
          {
            "code": "",
            "createTime": "2022-05-23 09:42:06",
            "value": "1528551814046244866",
            "judgeCount": 0,
            "multiCount": 1,
            "radioCount": 4,
            "remark": "vbn",
            "label": "vbn",
            "updateTime": "2022-05-23 09:42:06"
          },
          {
            "code": "",
            "createTime": "2022-05-30 18:02:30",
            "value": "1531214458792210434",
            "judgeCount": 0,
            "multiCount": 0,
            "radioCount": 12,
            "remark": "农业题库",
            "label": "农业题库",
            "updateTime": "2022-05-30 18:02:30"
          }
        ],
        "msg": "操作成功！",
        "success": true
      }
      question = response.data
    }


    // 题目类型点击事件，用来判断答案框是否显示
    const aaa = quType => {
      testShow.value = true
      postForm.values.repoList.push({
        radioCount: '',
        totalRadio: 0,
        radioScore: '',
        multiCount: '',
        totalMulti: 0,
        multiScore: '',
        judgeCount: '',
        judgeScore: '',
        totarepoIdlJudge: 0,
        totalJudge: 0,
        repoId: ''
      })
    };
    const handleChange = value => {
      question.forEach(que => {
        if (toRaw(value).repoId == que.value) {
          postForm.values.repoList.forEach(ans => {
            if (toRaw(value).repoId == toRaw(ans).repoId) {
              // 选择题库之后更新题库各类题的数量
              toRaw(ans).totalRadio = que.radioCount
              toRaw(ans).totalMulti = que.multiCount
              toRaw(ans).totalJudge = que.judgeCount
              // 这个赋值没啥用，但是一定要有，这个在页面上加载了，但是不显示，没有数据就不响应式
              postForm.values.poppp = [Math.floor(Math.random() * 3)]
            }
          })
        }
      })

      // console.log(`selected ${value}`);
    }


    // 删除一个 选项
    const removeDomain = item => {
      let index = postForm.values.repoList.indexOf(item);

      if (index !== -1) {
        postForm.values.repoList.splice(index, 1);
      }
      totalScoreChange()
    };
    // 添加一个 选项
    const addDomain = () => {
      if (postForm.values.value.quType == 3) {
        message.error("判断题只能拥有两个选项！！！")
      } else {
        postForm.values.repoList.push({
          isRight: false, content: '', analysis: '',
        });
      }
    };
    const onTimeChange = (value, dateString) => {
      postForm.values.startTime = dateString[0]
      postForm.values.endTime = dateString[1]
    };
    const totalScoreChange = () => {
      postForm.values.totalScore = 0

      postForm.values.repoList.forEach(function(item) {
        postForm.values.totalScore += item.radioCount * item.radioScore
        postForm.values.totalScore += item.multiCount * item.multiScore
        postForm.values.totalScore += item.judgeCount * item.judgeScore
      })

      // 赋值
    }
    // 进入页面就调用获取题库
    getQuestion()
    return {
      state,
      submit,
      cancel,
      formRef,
      formState,


      // 下面是上传图片所用接口

      quTypeDisabled,
      postForm,
      quTypes,
      levels,
      id,
      question,
      aaa,
      testShow,
      dateValues,
      value: ref([]),


      removeDomain,
      addDomain,
      locale,
      handleChange,
      itemImage,

      pagination,
      tableRef,
      fetch,
      columns,
      onSelectChange,
      onTimeChange,
      totalScoreChange,

    };


  },
});
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}

.dynamic-delete-button:hover {
  color: #777;
}

.dynamic-delete-button[disabled] {
  float: right;
  cursor: not-allowed;
  opacity: 0.5;
}
</style>
